package org.yang.loginunion.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * @author Billyang
 * @date 2024/8/6 10:41
 */
@Slf4j
public class HttpUtil {

    private static final int CONNECT_TIMEOUT = 5000;

    private static final int READ_TIMEOUT = 5000;

    private HttpUtil(){

    }

    public static String get(String url){
        try{
            URLConnection connection = new URL(url).openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            //当try块的代码执行完毕后，会自动调用inputStream的close方法关闭输入流，即使发生异常也能保证资源被正常关闭，具体原因见try-with-resources
            try (InputStream inputStream = connection.getInputStream()) {
                String response = IOUtils.toString(inputStream, Charset.forName("UTF-8"));
                log.debug("url:{},response:{}", url, response);
                return response;
            }
        }catch (IOException e){
            log.error("IOException error", e);
        }
        return null;
    }

}
